var _newname = "";
$(function(){
    var _txtpresentation_val = "";
    var _mode = "";
    var _membre = "";
    var current_file = "";
    var _filename = "";
	

    /* JQUERY_EXTEND */
    $.extend({ 		
		
        // ADHESION
        initAdhesion : function(){
            editorTXT('#txtadhesion');
			
            $("#jqGrid").jqGrid({
                // <MODIFICAR>
                url: './Queries/query-documents.php?id='+1+'nd='+new Date().getTime(),
                colNames:['int_id_lien_admin', '', 'Titre', 'Lien', 'Etat'],
                colModel:[
                {
                    hidden:true, 
                    search:false, 
                    name:'int_id_lien_admin', 
                    index:'int_id_lien_admin', 
                    align:'left'
                },

                {
                    name:'var_file_img',
                    width:20, 
                    index:'var_file_img', 
                    align:'center'
                },

                {
                    name:'var_lien_title', 
                    index:'var_lien_title', 
                    align:'left'
                },

                {
                    name:'var_lin_link', 
                    index:'var_lin_link', 
                    align:'left'
                },

                {
                    search:false, 
                    name:'var_htmldesc', 
                    index:'var_htmldesc',
                    width:40,  
                    align:'left'
                }
                ],
                sortname: ['int_id_lien_admin'],
                sortorder: "asc",
                width: 746,
                height: 250,
                // </MODIFICAR>
				
                loadtext: 'Chargement..',
                datatype: "json",
                pager: $('#jqpager'),
                rowNum:25,
                rowList:[25,50,75],	
                viewrecords: true,
                multiselect: true
            });
        }, 
        insertAdhesion : function(_var_lien_title,_var_lin_link,_var_file_single,_var_file_img,_int_id_administration,_int_id_state){
			
            $.post("./?ws=LiensAdmin&act=insertLien", {
                _var_lien_title:_var_lien_title,
                _var_lin_link:_var_lin_link,
                _var_file_single:_var_file_single,
                _var_file_img:_var_file_img,
                _int_id_administration:_int_id_administration,
                _int_id_state:_int_id_state, 
                cache:new Date().getTime()
                }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert($.trim(data));
                    $.modal.close();
                }
            });
        },
        updateAdhesion : function(_id, _var_lien_title,_var_lin_link,_var_file_single,_var_file_img,_int_id_administration,_int_id_state){
            $.post("./?ws=LiensAdmin&act=updateLien", {
                _id:_id, 
                _var_lien_title:_var_lien_title,
                _var_lin_link:_var_lin_link,
                _var_file_single:_var_file_single,
                _var_file_img:_var_file_img,
                _int_id_administration:_int_id_administration,
                _int_id_state:_int_id_state, 
                cache:new Date().getTime()
                }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert($.trim(data));
                    $.modal.close();
                }
                else $.modal.close();
            });
        },
        getAdhesion: function(_id){
            $.post("./?ws=LiensAdmin&act=getLien", {
                _id:_id, 
                cache:Math.random()
            }, function(data){
                if($.trim(data)!=""){
                    var _data = Array();
                    _data = data.split('_%_');
                    $('#txttitre').val( $.trim(_data[0]) ); 
                    $('#lbllien').html( $.trim(_data[1]) );
                    _newname = $.trim( _data[2]);
                    selectCbo( '#cboetat', $.trim( _data[3]) );	
                    iconError(false,"Document ajout&eacute;.");					
                    validateForm();
                }
            });
        },
        deleteAdhesion: function(_ids){
            $.post("./?ws=LiensAdmin&act=deleteLien", {
                _ids:_ids, 
                cache:Math.random()
            }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert(data);
                }
            });
        },
        getFilePath : function(_path){
            $.post("./?ws=LiensAdmin&act=getFilePath", {
                _path:_path, 
                cache:new Date().getTime()
                }, function(data){
                if($.trim(data)!=""){
                    $('#lbllien').html($.trim(data));	
                }
            });
        },
        uploadFile : function(_folder, _sizeLimit, _multi, photos){
            var current_file = "";
			
            $("#fileUpload").fileUpload({   
                uploader: './Resouces/js/uploader/uploader.swf',   
                cancelImg: './Resouces/js/uploader/cancel.png',   
                folder: _folder,   
                buttonText: 'Parcourir',
                checkScript: './Resouces/js/uploader/check.php',  
                width:110,
                height:35,
                fileDesc: "Format du document .PDF,.DOC,DOCX,.XLS,.XLSX,.JPG uniquement",
                fileExt: '*.pdf;*.docx;*.doc;*.xls;*.xlsx;*.jpg',
				
                sizeLimit: _sizeLimit,
                script: './Resouces/js/uploader/upload.php',   
                multi: _multi,   
                simUploadLimit: 1, 
				
                onProgress: function(event,queueID,fileObj,data){
                    current_file = queueID;
                    $("#btn-save").attr("disabled","-1");
                },
                onSelect: function(event,queueID,fileObj){
                    $('#lbl-okfile').html('');
                    $('#lbllien').html('');
                },
                onSelectOnce: function(event,data){
                    $('#fileUpload').fileUploadStart();
                },
                onCancel: function(event,queueID,fileObj,data){
                    $("#btn-save").removeAttr("disabled");
                },
                onError: function(event,queueID,fileObj,errorObj){
                    $("#btn-save").removeAttr("disabled");
                },
                onComplete: function(event,queueID,fileObj,response,data){
                    $("#btn-save").removeAttr("disabled");					
                    _newname = fileObj.name;
                    iconError(false,"Document ajout&eacute;.");
                    $.getFilePath(_newname);
                }
            }); 			
        }
    // END ADHESION

    });
    /* END JQUERY_EXTEND */
	
    function validateForm(){
        $('#txttitre').select();
        _form = $("#frm-Lien").validate({
            event: "blur",
            rules:{ 
                'txttitre': "required",
                'cboetat': "required"	
            },
            messages:{
                'txttitre': "Entrez le titre du document.",
                'cboetat': "S&eacute;lectionnez l'&eacute;tat"
            }
        });	
		
        function disabledControls(val){
            if(val){
                $('#txttitre').attr('disabled','-1'); 
                $('#cboetat').attr('disabled','-1');
            }
            else{
                $('#txttitre').removeAttr('disabled'); 
                $('#cboetat').removeAttr('disabled');

                $("#btn-save").removeAttr('disabled');
            }
        }

        // SAVE FORM
        $("#frm-Lien").submit(function(){
            if(_form.valid()){
                disabledControls(true);
				
                if(_mode == "update"){
                    if(_newname !=""){
                        $.updateAdhesion(_membre, $('#txttitre').val(), $('#lbllien').html(), _newname, "",1, $('#cboetat').val() );
                    }
                    else{ 
                        iconError(true, "S&eacute;lectionnez une image!");
                        disabledControls(false);
                    }
                }
                else{
                    if(_newname ==""){
                        iconError(true,"S&eacute;lectionnez un document!");
                        disabledControls(false);
                    }
                    else{
                        $.insertAdhesion( $('#txttitre').val(), $('#lbllien').html(), _newname, "",1, $('#cboetat').val() );
                    }
                }	
            }
			
            return false;
        });
    };
	
    function selectCbo(_idcbo, _intval){
        $(_idcbo+" option").each(function (){
            if($(this).val() == _intval){
                $(this).attr('selected','selected'); 
            }
        });
    }

    /*$("#get-Row").click( function(){
		var s = $("#jqGrid").getDataIDs();
		alert(s);
		$("#jqGrid").setSelection("2");
	});*/
	
    function iconError(_bool, _title){
        $('#lbl-okfile').css('display','none');
        var _icon = "";
        if(_bool) _icon = './Resouces/images/cancelfield.png';
        else _icon = './Resouces/images/okfield.png';
		
        $('#lbl-okfile').html('<img src="'+_icon+'" alt="'+_title+'" title="'+_title+'" />');
        $('#lbl-okfile').fadeIn();
    }
	
    function editorTXT(_textarea){
        $(_textarea).wysiwyg({
            controls : {
                separator00 : {
                    visible : true
                },
                justifyLeft: {
                    visible : true
                },
                justifyCenter: {
                    visible : false
                },
                justifyRight: {
                    visible : false
                },
                justifyFull: {
                    visible : true
                },
                underline: {
                    visible : true
                },
                insertImage:{
                    visible : false
                },
                subscript   : {
                    visible : false
                },
                superscript : {
                    visible : false
                },
                separator06 : {
                    separator : false
                },
                h1:{
                    visible : false
                },
                h2:{
                    visible : false
                },
                h3:{
                    visible : false
                },
                h1mozilla:{
                    visible : false
                },
                h2mozilla:{
                    visible : false
                },
                h3mozilla:{
                    visible : false
                },
                word    : {
                    exec: function(){}
                }
        }
        });
}
	
$("#btn-cancel").click( function(){
    $.modal.close();
});

$("#sinsert").click( function(){
    _mode = "insert";
    _filename = ""
		
    $('#Nouveau-title').html("Ajouter un document"); 
    $("#Nouveau").modal({
        position: [0,0],
        opacity: 25,
        autoResize: true,
        onOpen: function (dialog){
            dialog.overlay.fadeIn('fast', function (){
                dialog.container.fadeIn('fast', function (){
                    dialog.data.show();
                    $.uploadFile( '/csme.fr/documents', '15091456', false, false );
                    validateForm();
                });
            });
        }			
    });
});
	
$("#supdate").click(function(){
    var s = $("#jqGrid").getGridParam('selarrrow');
    _filename = ""
    _mode = "update";
    $('#Nouveau-title').html("Modifier le document");
    switch(s.length)
    {
        case 0:
            alert('Avertissement!\nS\u00E9lectionnez un document parmi la liste.');
            break;
			
        case 1:
            _membre = s[0];
            $.getAdhesion( _membre );
            $("#Nouveau").modal({
                position: [0,0],
                opacity: 45,
                autoResize: true,
                onOpen: function (dialog){
                    dialog.overlay.fadeIn('fast', function (){
                        dialog.container.fadeIn('fast', function (){
                            dialog.data.show();
                            $.uploadFile( '/csme.fr/documents', '15091456', false, false );
                            validateForm();
                        });
                    });
                }			
            });
            break;
			
        default:
            alert('Avertissement\nS\u00E9lectionnez seulement un lien \u00E0 la fois.');
            break;
    }
});

$("#sdelete").click(function(){
    if(_intUserT == 1){
        _mode = 'delete';
        var gr = $("#jqGrid").getGridParam('selrow');
	
        if( gr != null ) 
        {
            var s = $("#jqGrid").getGridParam('selarrrow');
            var f = s.toString();
            var j =  f.split(',');

            if(confirm("Eliminer document(s)\nVous avez selection\u00E9 "+j.length+" document(s).\nVoulez vous vraiment l'effacer(s)?")){
                $.deleteAdhesion(f);
            }
        }
        else{
            alert('Avertissement\nS\u00E9lectionnez les documents \u00E0 effacer.');
        }
    }
});


//Initializing
$.initAdhesion();

    });